﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using Microsoft.Xna.Framework.Content;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework;

namespace MyGames
{
    static public class GameLoader
    {
        static public ContentManager Content;

        static public void InitGameData(ContentManager content)
        {
            // Global content
            Content = content;

            // Read character value
            var fsCV = TitleContainer.OpenStream("Content/Data/CharInf.xml");
            XmlSerializer serCV = new XmlSerializer(typeof(List<CharacterInformation>));
            ModelInfomation.CharacterInformation = (List<CharacterInformation>)serCV.Deserialize(fsCV);
            fsCV.Close();

            // Read model frames
            var fsCF = TitleContainer.OpenStream("Content/Data/FrameInf.xml");
            var serCF = new XmlSerializer(typeof(List<FrameInformation>));
            ModelInfomation.FrameInformation = (List<FrameInformation>)serCF.Deserialize(fsCF);
            fsCF.Close();

            //Read item collection
            //ItemCollection.InitItems();

            // Load font
            Fonts.LoadContent();
        }

        static public MapData LoadMap(Locations location)
        {
#if WINDOWS
            XmlDocument doc = new XmlDocument();
            doc.Load("Content\\Data\\MapsInf.xml");

            string xpath = "/ArrayOfMapData/MapData[Location =" + '"' + location + '"' + "]";
            XmlNode node = doc.SelectSingleNode(xpath);

            XmlSerializer ser = new XmlSerializer(typeof(MapData));
            return (MapData)ser.Deserialize(new XmlNodeReader(node));
#else
            var fs = TitleContainer.OpenStream("Content/Data/MapsInf.xml");
            var ser = new XmlSerializer(typeof(List<MapData>));
            List<MapData> data = (List<MapData>)ser.Deserialize(fs);
            fs.Close();

            foreach (MapData map in data)
            {
                if (map.Location == location)
                    return map;
            }

            return new MapData();
#endif
        }

        static public bool CheckSaveFileExist()
        {
#if WINDOWS
            return File.Exists("Save/save.dat");
#else
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                return storage.FileExists("Save/save.dat");
            }
#endif
        }
    }
}
